<template>
  <div>
    <div class="title">
      <h3>《租赁协议》</h3>
    </div>
    <div class="box">
      <!-- 合约基本信息 -->
      <el-card style="margin-bottom: 20px" class="box1">
        <div class="header" slot="header">合约基本信息</div>
        <div class="conent1">
          <div>
            <!-- 房源信息 -->
            <el-row style="margin-bottom: 20px" :gutter="10">
              <el-col :span="24" class="box_title">
                1、房源信息
                <span class="box_lab1">所属小区 : {{ communityName }}</span>
              </el-col>
              <!-- crud -->
              <el-col :span="24">
                <avue-crud
                  ref="crud"
                  :option="housoption"
                  :data="housdata"
                  @row-del="del"
                  @row-update="addUpdate"
                >
                  <template slot="menuLeft">
                    <el-button
                      :disabled="!editShow"
                      @click="dialogTableVisible = true"
                      size="mini"
                      type="success"
                      >模板设置</el-button
                    >
                  </template>
                  <template
                    slot="menu"
                    slot-scope="{ row, index, size, type }"
                  ></template>
                </avue-crud>
              </el-col>
              <!-- crud-end -->
              <!-- 分摊信息 dashed  -->
              <el-col
                v-if="shareShow == 2"
                :span="24"
                class="box_title box_border"
              >
                <div style="margin-bottom: 15px; margin-top: 15px">
                  1-1.分摊信息
                </div>
                <el-col :span="8">
                  <div style="float: left; line-height: 28px; font-size: 12px">
                    客户：
                  </div>
                  <el-select
                    :disabled="!editShow"
                    size="mini"
                    style="width: 70%"
                    v-model="fictitiousContract.customerId"
                    placeholder="请选择客户"
                    @change="getCustomerAccountList2"
                  >
                    <el-option
                      v-for="item in customerList"
                      :key="item.id"
                      :label="item.customerName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <div style="float: left; line-height: 28px; font-size: 12px">
                    付款账户：
                  </div>
                  <el-select
                    :disabled="!editShow"
                    size="mini"
                    style="width: 70%"
                    v-model="fictitiousContract.paymentAccountId"
                    placeholder="请选择付款账户"
                  >
                    <el-option
                      v-for="item in customerAccountList2"
                      :key="item.id"
                      :label="item.accountName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <div style="float: left; line-height: 28px; font-size: 12px">
                    分摊比例(%)：
                  </div>
                  <el-input
                    :disabled="!editShow"
                    size="mini"
                    @change="shareChange"
                    style="width: 70%"
                    v-model="fictitiousContract.sharePercent"
                    placeholder="请填写分摊比例"
                  ></el-input>
                </el-col>
              </el-col>
              <!-- end -->
            </el-row>
            <!-- 租客信息 -->
            <el-row :gutter="10">
              <el-col :span="24" class="box_title">
                2、租客信息
                <span class="box_lab1">多人入住，共用一张充值和扣费的卡</span>
              </el-col>
              <el-col class="form_item_top" :span="24">
                <!-- 所属客户： -->
                <el-col :span="10">
                  <div style="float: left; line-height: 40px; font-size: 14px">
                    所属客户：
                  </div>
                  <el-select
                    :disabled="!editShow"
                    @change="getCustomerAccountList1"
                    style="width: 80%"
                    v-model="form.customerId"
                    placeholder="请选择客户"
                  >
                    <el-option
                      v-for="item in customerList"
                      :key="item.id"
                      :label="item.customerName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-col>
                <!-- 付款账户： -->
                <el-col :span="10">
                  <div style="float: left; line-height: 40px; font-size: 14px">
                    付款账户：
                  </div>
                  <el-select
                    :disabled="!editShow"
                    style="width: 80%"
                    v-model="form.paymentAccountId"
                    placeholder="请选择付款账户"
                  >
                    <el-option
                      v-for="item in customerAccountList1"
                      :key="item.id"
                      :label="item.accountName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-col>
              <el-col v-for="(item, index) in userList" :key="index" :span="24">
                <!-- 租客姓名： -->
                <el-col :span="10">
                  <div class="box_lab box_lab_left">用户姓名：</div>
                  <el-select
                    :disabled="!editShow"
                    @change="getMobile(index, item.id)"
                    class="box-width-8"
                    v-model="item.id"
                    placeholder="请选择用户姓名"
                  >
                    <el-option
                      v-for="item in userData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-col>
                <!-- 租客手机号： -->
                <el-col :span="10">
                  <div class="box_lab box_lab_left">用户手机号：</div>
                  <el-input
                    disabled
                    style="width: 75%"
                    v-model="item.mobile"
                    placeholder="手机号"
                  ></el-input>
                </el-col>
                <!-- btn -->
                <el-col :span="4">
                  <el-button
                    :disabled="!editShow"
                    @click="delUser(index)"
                    v-if="userList.length > 1"
                    type="danger"
                    icon="el-icon-delete"
                    circle
                  ></el-button>
                </el-col>
              </el-col>
              <!-- addBtn -->
              <el-col
                v-if="userList.length < 5 && editShow"
                :span="20"
                class="box_title"
              >
                <el-button
                  @click="addUser"
                  style="width: 100%"
                  size="mini"
                  type="primary"
                  class="el-icon-plus"
                  plain
                  >添加租客</el-button
                >
              </el-col>
            </el-row>
            <!-- 收款账户 -->
            <el-row :gutter="10">
              <el-col :span="24" class="box_title">3、收款账户:</el-col>
              <el-col :span="24">
                <el-col :span="10">
                  <el-select
                    disabled
                    style="width: 100%"
                    v-model="form.receiptAccountId"
                    placeholder="请选择收款账户"
                  >
                    <el-option
                      v-for="item in receiptAccount"
                      :key="item.id"
                      :label="item.accountName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-col>
            </el-row>
            <!-- 生效时间 -->
            <el-row :gutter="10">
              <el-col :span="24" class="box_title">4、生效时间</el-col>
              <el-col :span="24">
                <el-col :span="10">
                  <p class="box_lab">
                    合约生效时间：
                    <span class="box_lab1">合约生效之后开始计算费用</span>
                  </p>
                  <el-date-picker
                    disabled
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    v-model="form.startDate"
                    type="date"
                    placeholder="选择日期"
                  ></el-date-picker>
                </el-col>
              </el-col>
            </el-row>
            <!-- end -->
          </div>
        </div>
      </el-card>
      <!-- 费用管理设置 -->
      <el-card class="box1">
        <div class="header" slot="header">费用管理设置</div>
        <div class="conent">
          <div>
            <!-- 合约类型 -->
            <el-row :gutter="10">
              <el-col :span="24" class="box_title">
                1、合约类型
                <span class="box_lab1">后付费合约欠费将不会拉闸</span>
              </el-col>
              <el-col :span="24">
                <el-col :span="10">
                  <el-radio-group
                    disabled
                    style="margin: 10px"
                    v-model="form.contractType"
                  >
                    <el-radio :label="1">预付费</el-radio>
                    <el-radio :label="2">后付费</el-radio>
                  </el-radio-group>
                </el-col>
              </el-col>
            </el-row>
            <!-- 透支额度 -->
            <el-row :gutter="10">
              <el-col :span="24" class="box_title">
                2、透支额度
                <span class="box_lab1"
                  >若设备不是您购买的，透支额度不可超过￥20</span
                >
              </el-col>
              <el-col :span="24">
                <el-col :span="10">
                  <p></p>
                  <el-input
                    disabled
                    v-model="form.overAmount"
                    placeholder="额度"
                  ></el-input>
                </el-col>
              </el-col>
            </el-row>
            <!-- 充值通道费 -->
            <el-row :gutter="10">
              <el-col :span="24" class="box_title">3 、充值通道费(%)</el-col>
              <el-col :span="24">
                <el-col :span="10">
                  <p></p>
                  <el-input
                    disabled
                    v-model="form.chargeFee"
                    placeholder="充值通道费"
                  ></el-input>
                </el-col>
                <el-col :span="10">
                  <span class="box_lab">充值通道费由谁承担：</span>
                  <el-radio-group
                    disabled
                    style="margin: 10px"
                    v-model="form.deductType"
                  >
                    <el-radio :label="1">租客承担</el-radio>
                    <el-radio :label="2">商户承担</el-radio>
                  </el-radio-group>
                  <div>
                    <span class="box_lab1"
                      >举例：假设通道费为0.6%，如果租客充值￥100，租客的卡到账￥100，商户的收入要减去该通道费￥0.6</span
                    >
                  </div>
                </el-col>
              </el-col>
            </el-row>
            <!-- end_btn -->
            <div style="text-align: center; margin-top: 20px">
              <el-button
                v-if="editShow"
                @click="editShow = false"
                size="mini"
                style="margin-right: 20px"
                type="primary"
                >取消</el-button
              >
              <el-button
                v-if="!editShow"
                @click="last"
                size="mini"
                style="margin-right: 20px"
                type="primary"
                >返回</el-button
              >
              <el-button
                v-if="!editShow"
                @click="editShow = true"
                size="mini"
                style="margin-right: 20px"
                type="primary"
                >编辑</el-button
              >
              <el-button v-if="editShow" @click="add" size="mini" type="primary"
                >保存</el-button
              >
            </div>
            <!-- end -->
          </div>
        </div>
      </el-card>
    </div>
    <!-- 计费模板-dialog -->
    <el-dialog
      class="dialog"
      :append-to-body="true"
      title="计费模板"
      :visible.sync="dialogTableVisible"
      width="60%"
      @open="getTemplateList(page)"
    >
      <avue-crud
        @selection-change="selectionChange"
        :data="data1"
        :option="option2"
      >
        <template slot="menu" slot-scope="{ row, index, size, type }">
          <el-button
            :disabled="row.id == feeTemplateId"
            @click="getFeeTemplate(row)"
            :size="size"
            :type="type"
            >{{ feeTemplateId == row.id ? "已使用" : "使用" }}</el-button
          >
        </template>
      </avue-crud>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoomDetail,
  getAppellation,
  getCustomerAccountList,
  getCustomerMember,
  getReceiptAccountList,
  add,
  getTemplateList,
  getDetail,
  update,
} from "@/api/contract/share";
export default {
  name: "shareEditor",
  data() {
    return {
      obj: {},
      housdata1: [],
      editShow: false,
      shareShow: 1, // 分摊显示
      feeTemplateId: "", //计费模板
      form: {
        customerId: "", // 客户id
        paymentAccountId: "", // 付款账户ID
        receiptAccountId: "", // 收款账户id
        startDate: "", // 生效日期
        contractType: 1, // 合同类型：1、预付费；2、后付费
        overAmount: "", // 透支额度
        chargeFee: "", // 手续费
        deductType: 1, // 手续费扣减方式：1、租客承担；2、商户承担
        //---
        customerName: "", // 客户名称
      },
      //分摊信息
      fictitiousContract: {
        customerId: "", // 客户ID
        customerName: "", // 客户名称
        paymentAccount: "", // 账户名称
        paymentAccountId: "", // 账户ID
        sharePercent: "", // 分摊比例
      },
      roomShareRateDTOS: [], // 房间列表信息
      customerList: [], // 客户list
      receiptAccountList: [], // 收款账户列表
      customerAccountList1: [], // 客户付款list
      customerAccountList2: [], // 虚拟客户付款list
      memberIds: [], // 用户列表
      shareValue: "",
      housdata: [],
      housoption: {
        addBtn: false,
        editBtn: false,
        addRowBtn: false,
        delBtn: false,
        cellBtn: true,
        menuWidth: 250,
        columnBtn: false,
        refreshBtn: false,
        column: [
          {
            label: "房间号",
            prop: "roomName",
            // cell: true,
            width: "150px",

            // change: ({ value, column }) => {
            //   if (value) {
            //     this.housChang(value);
            //   }
            // },
            // rules: [
            //   {
            //     required: true,
            //     message: "请输入房间号",
            //     trigger: "blur",
            //   },
            // ],
          },
          {
            label: "设备编号",
            prop: "sn",
          },
          {
            label: "设备规格",
            prop: "spec",
            type: "select",
            dicData: [
              {
                label: "单相电表",
                value: "1",
              },
              {
                label: "三相电表",
                value: "2",
              },
            ],
            // cell: true,
          },
          {
            label: "当前状态",
            prop: "status",
            dicData: [
              {
                label: "在线",
                value: 1,
              },
              {
                label: "离线",
                value: 0,
              },
            ],
          },
          {
            label: "最近读数",
            prop: "readValue",
          },
          {
            label: "设置计费始读数",
            prop: "start",
            width: "150px",
            cell: true,
            rules: [
              {
                required: true,
                message: "请输入计费始读数",
                trigger: "blur",
              },
            ],
          },
          {
            label: "计费模板",
            prop: "feeTemplateName",
          },
          {
            label: "计费模板id",
            prop: "feeTemplateId",
            hide: true,
          },
          {
            label: "房间id",
            prop: "roomId",
            hide: true,
          },
          {
            label: "费用比例(%)",
            prop: "sharedPercent",
          },
        ],
      },
      userList: [
        {
          id: "",
        },
      ],
      houseShow: true,
      value: "",
      userData: [],
      dialogTableVisible: false,
      radio: 3,
      radio1: 1,
      activeName: "first",
      communityName: "",
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option1: {
        menu: false,
        page: false,
        addBtn: false,
        align: "center",
        menuAlign: "center",
        column: [
          {
            label: "设备编号",
            prop: "name",
          },
          {
            label: "设备类型",
            prop: "sex",
          },
          {
            label: "设备属性",
            prop: "name",
          },
          {
            label: "当前状态",
            prop: "name",
          },
          {
            label: "最近读数",
            prop: "name",
          },
          {
            label: "设置计费始读数",
            prop: "name",
          },
          {
            label: "选择计费模板",
            prop: "name",
          },
          {
            label: "费用比例(%)",
            prop: "name",
          },
        ],
      },
      data: [],
      option2: {
        page: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        selection: false,
        selectable: (row, index) => {
          if (this.list.length >= 1) {
            if (row.name == this.list[0]["name"]) {
              return index === row.$index;
            }
          } else {
            return true;
          }
        },
        align: "center",
        menuAlign: "center",
        column: [
          {
            label: "模板名称",
            prop: "templateName",
          },
          {
            label: "模板id",
            prop: "id",
            hide: true,
          },
          {
            label: "计费模式",
            prop: "feeType",
            type: "select",
            dicData: [
              {
                label: "无",
                value: 0,
              },
              {
                label: "平均",
                value: 1,
              },
              {
                label: "峰谷",
                value: 2,
              },
              {
                label: "阶梯",
                value: 3,
              },
            ],
          },
          {
            label: "结算周期",
            prop: "settlementCycle",
            formatter: (row, value) => {
              return `${value}天`;
            },
          },
        ],
      },
      data1: [],
      list: [],
      received: {
        id: "",
        type: "",
        communityId: "",
        roomid: "",
        contractId: "",
      },
    };
  },
  mounted() {
    // this.received.type = this.$route.query.type;
    this.received.contractId = this.$route.query.contractId;
    // 获取房间设备
    // if (this.received.type == "add") {
    //   this.received.communityId = this.$route.query.communityId;
    //   this.received.roomid = this.$route.query.roomid;
    //   this.getRoomDetail(this.received.communityId, this.received.roomid);
    // }
    this.getAppellation(); //客户列表
    this.getReceiptAccountList();
    this.getDetail(this.received.contractId);
  },
  watch: {
    housdata() {
      if (this.housdata.length == 0) {
        this.housdata = this.deepClone(this.housdata1);
      }
    },
  },
  methods: {
    getDetail(id) {
      getDetail(id).then((res) => {
        const data = res.data.data.commonContract;
        if (res.data.data.fictitiousContract) {
          this.shareShow = 2;
          const fictitiousContractData = res.data.data.fictitiousContract;
          this.fictitiousContract = fictitiousContractData;
        } else {
          this.shareShow = 1;
        }
        const memberIds = res.data.data.memberIds;
        this.communityName = data.communityName;
        this.housdata = data.roomShareRateDTOS;
        data.roomShareRateDTOS.forEach((item) => {
          item.roomName = item.roomNo;
        });
        this.feeTemplateId = data.feeTemplateId;
        let feeTemplateName = data.feeTemplateName;
        // this.shareShow = data.contractClass;
        this.housdata.forEach((item) => {
          item.sn = item.meterId;
          this.$set(item, "feeTemplateId", this.feeTemplateId);
          this.$set(item, "feeTemplateName", feeTemplateName);
        });
        this.housdata1 = this.deepClone(this.housdata);
        this.getCustomerAccountList1(data.customerId);
        this.getCustomerAccountList2(data.customerId);
        this.getCustomerMember(data.customerId);
        // this.userList = memberIds;
        if (memberIds.length > 0) {
          getCustomerMember(data.customerId).then((res) => {
            this.userData = res.data.data;
            this.userList = [];
            memberIds.forEach((item) => {
              const mobile = this.userData.find((em) => em.id == item);
              mobile.disabled = true;
              if (mobile && mobile.phone) {
                this.userList.push({
                  id: item,
                  mobile: mobile.phone,
                });
              }
            });
          });
        }
        this.form = data;
        // this.fictitiousContract = fictitiousContractData;
      });
    },
    // 模板列表
    getTemplateList(page, params = {}) {
      getTemplateList(
        page.currentPage,
        page.pageSize,
        Object.assign(params)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data1 = data.records;
      });
    },
    // 收款账户列表
    getReceiptAccountList() {
      getReceiptAccountList().then((res) => {
        this.receiptAccount = res.data.data;
      });
    },
    // 用户列表
    getCustomerMember(id) {
      getCustomerMember(id).then((res) => {
        this.userData = res.data.data;
      });
    },
    // 虚拟客户付款账户
    getCustomerAccountList2(id) {
      getCustomerAccountList(id).then((res) => {
        this.customerAccountList2 = res.data.data.records;
      });
    },
    // 选中客户-付款账户-用户列表
    getCustomerAccountList1(id) {
      getCustomerAccountList(id).then((res) => {
        this.customerAccountList1 = res.data.data.records;
      });
      this.getCustomerMember(id);
    },
    // 客户列表
    getAppellation(name) {
      getAppellation(name).then((res) => {
        this.customerList = res.data.data;
      });
    },
    // 获取房间设备
    getRoomDetail(communityId, roomid) {
      getRoomDetail(communityId, roomid).then((res) => {
        const data = res.data.data;
        // this.housdata1 = this.deepClone(data);
        this.communityName = data[0]["roomName"].split("->")[0];
        this.housdata.sharedPercent = 100;
        data.forEach((item) => {
          item.sharedPercent = 100;
          // item.$cellEdit = true;
        });
        this.housdata = data;
        this.housdata1 = this.deepClone(data);
      });
    },
    // 分摊比例计算
    shareChange(value) {
      if (value >= 0 && value <= 100) {
        let str = 100 - value;
        this.housdata.forEach((item) => {
          item.sharedPercent = str;
        });
      } else {
        this.$notify({
          title: "提示",
          message: "请输入0-100以内的正整数",
          type: "warning",
        });
      }
    },
    //新增房间计算
    housChang(value) {
      const index = this.housdata.findIndex((item) => item.roomName == value);
      if (index != -1) {
        let data = {
          sharedPercent: 100,
          device: 2,
          roomName: value,
          status: 1,
          deviceid: 1,
          dushu: 100,
          shidushu: value + 4,
          moban: 1,
        };
        this.housdata[index] = data;
      }
    },
    // 保存
    add() {
      this.getDataForm();
      update(this.obj).then((res) => {
        this.$notify({
          message: res.data.msg,
          type: "success",
        });
        this.last();
      });
    },
    // 新增房间保存
    addUpdate(form, index, done, loading) {
      loading();
      done();
    },
    // 新增房间
    addNextRow(index) {
      this.housdata.splice(this.housdata.length, 0, {
        $cellEdit: true,
      });
    },
    // 删除房间
    del(row, index) {
      if (this.housdata.length != 1) {
        this.housdata.splice(index, 1);
      } else {
        this.$notify({
          title: "提示",
          message: "最少需要有一条房间信息",
          type: "warning",
        });
      }
    },
    // 返回
    last() {
      this.$router.go(-1);
    },
    // 删除租客
    delUser(index) {
      this.userList.splice(index, 1);
    },
    // 新增租客
    addUser() {
      this.userList.push({
        roomName: "",
        userName: "",
        telephone: "",
        proportion: "",
      });
    },
    // 模板选择
    getFeeTemplate(row) {
      this.housdata.forEach((item) => {
        // item.feeTemplateName = row.name;
        this.$set(item, "feeTemplateName", row.templateName);
        this.$set(item, "feeTemplateId", row.id);
        this.feeTemplateId = row.id;
        this.dialogTableVisible = false;
        // item.feeTemplateId = row.id;
      });
    },
    // 格式转换
    getDataForm() {
      let roomShareRateDTOS = [];
      this.userList.forEach((item) => {
        this.memberIds.push(item.id);
      });
      this.housdata.forEach((item) => {
        roomShareRateDTOS.push({
          meterId: item.sn,
          roomId: item.roomId,
          sharedPercent: item.sharedPercent,
          start: item.start,
        });
      });
      if (this.shareShow == 2) {
        this.obj.fictitiousContract = this.fictitiousContract;
      }
      this.form.contractClass = this.shareShow;
      this.form.feeTemplateId = this.feeTemplateId;
      this.form.roomShareRateDTOS = roomShareRateDTOS;
      this.obj.commonContract = this.form;
      this.obj.memberIds = this.memberIds;
    },
    // 手机号
    getMobile(index, id) {
      const data = this.userData.find((item) => item.id == id);
      data.disabled = true;
      this.userList[index]["mobile"] = data.mobile;
    },
    // end
  },
};
</script>

<style scoped lang='scss'>
.avue-view {
  padding: 0 !important;
}

.title {
  height: 80px;
  text-align: center;
  line-height: 80px;
  background-color: #fff;
  h3 {
    margin-top: 0;
  }
}

.box {
  padding: 16px;
  margin-bottom: 40px;

  .header {
    font-weight: 700;
    font-size: 16px;
    margin: 16px;
  }
}
.box_border {
  border: 1px dashed #ccc;
  padding: 5px;
  padding-left: 20px !important;
  border-radius: 3px;
  font-size: 12px !important;
  background-color: rgb(240, 242, 245);
}

.box1 {
  border-radius: 4px;
  border: 1px solid #e6ebf5 !important;
  /deep/.el-tabs__header {
    margin-left: 5px;
  }
}

.box_lab {
  font-size: 14px;
  color: #606266;
}

.box_lab_left {
  float: left;
  line-height: 40px;
}
.box-width-8 {
  width: 80%;
}

.box_lab1 {
  font-size: 12px;
  color: #909399;
}

.box_title {
  font-size: 16px;
}

.dialog {
  /deep/.avue-crud__menu {
    display: none;
  }
}

.conent1 {
  /deep/.avue-crud__pagination {
    display: none;
  }
}
.form_item_top {
  margin-top: 10px;
}
</style>